import 'dart:async';

import 'package:enjoy_plus_flutter_7/api/login.dart';
import 'package:enjoy_plus_flutter_7/eventBus/event_bus.dart';
import 'package:enjoy_plus_flutter_7/utils/TokenManager.dart';
import 'package:enjoy_plus_flutter_7/utils/toast.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController codeController = TextEditingController();
  int _count = 6;
  Timer? _timer;
  bool flag = false;

  //彻底销毁钩子
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer?.cancel(); //离开页面时清除定时器
  }

  void beginCount() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _count--;
      });
      if (_count == 0) {
        timer.cancel();
        setState(() {
          _count = 6;
        });
        flag = false;
      }
    });
  }

  Widget getTextWidget() {
    if (_count < 6) {
      return Text('$_count秒后获取验证码');
    } else {
      return const Text('获取验证码');
    }
  }

  void sentCode() async {
    if (phoneController.text.isEmpty) {
      return PromptAction.error('请输入手机号');
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phoneController.text)) {
      return PromptAction.error('手机号格式不对');
    }
    if (flag) return;
    flag = true;
    // PromptAction.success('成功');
    //发送请求
    var code = await sendCodeAPI({'mobile': phoneController.text});
    print(code);

    beginCount();
  }

  Future<void> getLogin() async {
    if (phoneController.text.isEmpty) {
      return PromptAction.error('手机号不能为空！！');
    }
    if (codeController.text.isEmpty) {
      return PromptAction.error('验证码不能为空！！');
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phoneController.text)) {
      return PromptAction.error('手机号格式不对');
    }
    if (!RegExp(r'^\d{6}$').hasMatch(codeController.text)) {
      return PromptAction.error('验证码格式不对');
    }
    var res = await userLoginAPI(
        {'mobile': phoneController.text, 'code': codeController.text});
    print(res);
    _timer?.cancel();
    PromptAction.success('登录成功');
    event_bus.fire(LogSccessEvent());
    tokenManager.setPre(res['token'], refreshToken: res['refreshToken']);
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    //0.验证手机号
                    sentCode();
                    //1.发请求
                    //2.倒计时
                    // beginCount();
                  },
                  child: getTextWidget(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      getLogin();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
